#include "DockingSplitter.h"
#include "DockingTabStack.h"
#include "DockingArea.h"
#include <QDragEnterEvent>
#include <QMimeData>
#include <QChildEvent>
#include <QTimer>
#include <cassert>

DockingSplitter::DockingSplitter(Qt::Orientation orientation, QWidget* parent)
    : QSplitter(orientation, parent)
    , m_parentArea(nullptr)
    , m_autoCollapseEnabled(true)
    , m_autoRemoveEmptyChildren(true)
{
    setupSplitter();
}

DockingSplitter::DockingSplitter(DockingArea* parentArea, Qt::Orientation orientation, QWidget* parent)
    : QSplitter(orientation, parent)
    , m_parentArea(parentArea)
    , m_autoCollapseEnabled(true)
    , m_autoRemoveEmptyChildren(true)
{
    setupSplitter();
}

DockingSplitter::~DockingSplitter()
{
    // QSplitter会自动清理子widget
}

void DockingSplitter::setupSplitter()
{
    // 设置拖放支持
    setAcceptDrops(true);
    
    // 设置基础样式
    setChildrenCollapsible(false); // 防止子组件被完全折叠
    setHandleWidth(4);
    
    // 样式由QSS控制
}

// === 子节点管理 ===

DockingTabStack* DockingSplitter::addTabStack(int index)
{
    DockingTabStack* tabStack = new DockingTabStack(this, this);
    
    if (index < 0 || index >= count())
    {
        addWidget(tabStack);
        index = count() - 1;
    }
    else
    {
        insertWidget(index, tabStack);
    }
    
     connectChildSignals(tabStack);
     emit childAdded(tabStack, index);
    
    return tabStack;
}

DockingSplitter* DockingSplitter::addSplitter(Qt::Orientation orientation, int index) {
    DockingSplitter* splitter = new DockingSplitter(m_parentArea, orientation, this);
    
    if (index < 0 || index >= count()) {
        addWidget(splitter);
        index = count() - 1;
    } else {
        insertWidget(index, splitter);
    }
    
    connectChildSignals(splitter);
    emit childAdded(splitter, index);
    
    return splitter;
}

void DockingSplitter::removeChild(QWidget* child) {
    if (!child) return;
    
    int index = indexOf(child);
    if (index >= 0) {
        removeChild(index);
    }
}

void DockingSplitter::removeChild(int index) {
    if (index < 0 || index >= count()) return;
    
    QWidget* child = widget(index);
    if (!child) return;
    
    // 先断开信号连接
    disconnectChildSignals(child);
    
    // 发出移除信号（在实际移除之前）
    emit childRemoved(child, index);
    
    // 从QSplitter中移除子控件
    // 注意：setParent(nullptr) 会自动从QSplitter中移除子控件
    child->setParent(nullptr);
    
    // 检查是否需要折叠或清理
    if (isEmpty()) {
        emit splitterBecameEmpty();
    } else {
        collapseIfNeeded();
    }
}

// === 动态布局 ===

void DockingSplitter::collapseIfNeeded() {
    if (!m_autoCollapseEnabled || !shouldAutoCollapse()) return;
    
    if (hasOnlyOneChild()) {
        emit splitterCollapsed();
        // 具体的折叠逻辑由父容器处理
    }
}

// === 子节点查询 ===

QList<DockingTabStack*> DockingSplitter::getAllTabStacks() const {
    QList<DockingTabStack*> result;
    
    for (int i = 0; i < count(); ++i) {
        QWidget* child = widget(i);
        
        if (auto tabStack = qobject_cast<DockingTabStack*>(child)) {
            result.append(tabStack);
        } else if (auto splitter = qobject_cast<DockingSplitter*>(child)) {
            result.append(splitter->getAllTabStacks());
        }
    }
    
    return result;
}

QList<DockingSplitter*> DockingSplitter::getAllSplitters() const {
    QList<DockingSplitter*> result;
    
    for (int i = 0; i < count(); ++i) {
        QWidget* child = widget(i);
        
        if (auto splitter = qobject_cast<DockingSplitter*>(child)) {
            result.append(splitter);
            result.append(splitter->getAllSplitters());
        }
    }
    
    return result;
}

DockingTabStack* DockingSplitter::findTabStackContaining(QWidget* content) const {
    if (!content) return nullptr;
    
    for (int i = 0; i < count(); ++i) {
        QWidget* child = widget(i);
        
        if (auto tabStack = qobject_cast<DockingTabStack*>(child)) {
            // 检查TabStack中是否包含指定内容
            for (int j = 0; j < tabStack->tabCount(); ++j) {
                if (tabStack->contentAt(j) == content) {
                    return tabStack;
                }
            }
        } else if (auto splitter = qobject_cast<DockingSplitter*>(child)) {
            DockingTabStack* found = splitter->findTabStackContaining(content);
            if (found) return found;
        }
    }
    
    return nullptr;
}

// === 分割比例管理 ===

void DockingSplitter::setSplitRatios(const QList<double>& ratios) {
    if (ratios.size() != count()) return;
    
    QList<int> sizes;
    int totalSize = (orientation() == Qt::Horizontal) ? width() : height();
    
    for (double ratio : ratios) {
        sizes.append(static_cast<int>(totalSize * ratio));
    }
    
    setSizes(sizes);
}

QList<double> DockingSplitter::getSplitRatios() const {
    QList<double> ratios;
    QList<int> sizes = this->sizes();
    
    if (sizes.isEmpty()) return ratios;
    
    int totalSize = 0;
    for (int size : sizes) {
        totalSize += size;
    }
    
    if (totalSize == 0) return ratios;
    
    for (int size : sizes) {
        ratios.append(static_cast<double>(size) / totalSize);
    }
    
    return ratios;
}

void DockingSplitter::resetToEqualSizes() {
    if (count() == 0) return;
    
    QList<int> sizes;
    int totalSize = (orientation() == Qt::Horizontal) ? width() : height();
    int sizePerChild = totalSize / count();
    
    for (int i = 0; i < count(); ++i) {
        sizes.append(sizePerChild);
    }
    
    setSizes(sizes);
}

// === Qt事件重写 ===

void DockingSplitter::childEvent(QChildEvent* event) {
    QSplitter::childEvent(event);
    
    if (event->type() == QEvent::ChildAdded) {
        if (QWidget* widget = qobject_cast<QWidget*>(event->child())) {
            connectChildSignals(widget);
        }
    } else if (event->type() == QEvent::ChildRemoved) {
        if (QWidget* widget = qobject_cast<QWidget*>(event->child())) {
            // 不在这里断开信号连接，让Qt自然处理
            // disconnectChildSignals 会在 removeChild 中被调用
        }
        
        // 清理空子节点
        if (m_autoRemoveEmptyChildren) {
            QTimer::singleShot(0, this, &DockingSplitter::cleanupEmptyChildren);
        }
    }
}

void DockingSplitter::resizeEvent(QResizeEvent* event) {
    QSplitter::resizeEvent(event);
}

// === 拖放支持 ===

void DockingSplitter::dragEnterEvent(QDragEnterEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        event->acceptProposedAction();
    } else {
        QSplitter::dragEnterEvent(event);
    }
}

void DockingSplitter::dragMoveEvent(QDragMoveEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        event->acceptProposedAction();
    } else {
        QSplitter::dragMoveEvent(event);
    }
}

void DockingSplitter::dragLeaveEvent(QDragLeaveEvent* event) {
    QSplitter::dragLeaveEvent(event);
}

void DockingSplitter::dropEvent(QDropEvent* event) {
    if (event->mimeData()->hasFormat("application/x-docktab")) {
        // 在放置位置创建新的TabStack来接收标签
        QPoint pos = event->position().toPoint();
        
        // 简单实现：在末尾添加新的TabStack
        DockingTabStack* newStack = addTabStack();
        
        // 转发拖放事件到新的TabStack
        QDropEvent newEvent(pos, event->possibleActions(), event->mimeData(), 
                          event->buttons(), event->modifiers());
        bool accepted = newStack->handleDropEvent(&newEvent);
        
        if (accepted) {
            event->acceptProposedAction();
        }
    } else {
        QSplitter::dropEvent(event);
    }
}

// === 槽函数 ===

void DockingSplitter::onChildTabStackBecameEmpty() {
    if (!m_autoRemoveEmptyChildren) return;
    
    DockingTabStack* emptyStack = qobject_cast<DockingTabStack*>(sender());
    if (emptyStack && emptyStack->parent() == this) {
        qDebug() << "自动移除空的TabStack:" << emptyStack;
        // 暂时禁用自动清理，避免级联删除
        bool wasAutoRemoveEnabled = m_autoRemoveEmptyChildren;
        m_autoRemoveEmptyChildren = false;
        
        // 使用更安全的删除方式
        emptyStack->setParent(nullptr);
        emptyStack->deleteLater();
        
        // 恢复自动清理设置
        m_autoRemoveEmptyChildren = wasAutoRemoveEnabled;
    }
}

void DockingSplitter::onChildSplitterBecameEmpty() {
    if (!m_autoRemoveEmptyChildren) return;
    
    DockingSplitter* emptySplitter = qobject_cast<DockingSplitter*>(sender());
    if (emptySplitter && emptySplitter->parent() == this) {
        qDebug() << "自动移除空的Splitter:" << emptySplitter;
        // 暂时禁用自动清理，避免级联删除
        bool wasAutoRemoveEnabled = m_autoRemoveEmptyChildren;
        m_autoRemoveEmptyChildren = false;
        
        // 使用更安全的删除方式
        emptySplitter->setParent(nullptr);
        emptySplitter->deleteLater();
        
        // 恢复自动清理设置
        m_autoRemoveEmptyChildren = wasAutoRemoveEnabled;
    }
}

// === 私有函数 ===

void DockingSplitter::connectChildSignals(QWidget* child) {
    if (!child) return;
    
    if (auto tabStack = qobject_cast<DockingTabStack*>(child)) {
        connect(tabStack, &DockingTabStack::stackBecameEmpty, 
                this, &DockingSplitter::onChildTabStackBecameEmpty);
    } else if (auto splitter = qobject_cast<DockingSplitter*>(child)) {
        connect(splitter, &DockingSplitter::splitterBecameEmpty, 
                this, &DockingSplitter::onChildSplitterBecameEmpty);
    }
}

void DockingSplitter::disconnectChildSignals(QWidget* child) {
    if (!child) return;
    
    disconnect(child, nullptr, this, nullptr);
}

void DockingSplitter::cleanupEmptyChildren() {
    for (int i = count() - 1; i >= 0; --i) {
        QWidget* child = widget(i);
        
        bool shouldRemove = false;
        
        if (auto tabStack = qobject_cast<DockingTabStack*>(child)) {
            shouldRemove = tabStack->isEmpty();
        } else if (auto splitter = qobject_cast<DockingSplitter*>(child)) {
            shouldRemove = splitter->isEmpty();
        }
        
        if (shouldRemove) {
            // 使用更安全的删除方式
            child->setParent(nullptr);
            child->deleteLater();
        }
    }
    
    if (isEmpty()) {
        emit splitterBecameEmpty();
    }
}

bool DockingSplitter::shouldAutoCollapse() const {
    return hasOnlyOneChild() && m_autoCollapseEnabled;
}
